package com.base.core.util;

import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * 
 * @author TangJie
 *
 */
public class AESUtils {
	
	     private static String strDefaultKey = "suneee";
	     private static final String ENCODING = "UTF-8";
	     private static final String KEY_ALGORITHM = "AES";//产生密钥的算法	     	  	      	      
	      /**
	       * AES加密
	       * @param data     带加密数据
	       * @param keyByte  密钥
	       */
	      public static byte[] encrypt(String password) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException,NoSuchPaddingException, IllegalBlockSizeException,BadPaddingException, UnsupportedEncodingException, NoSuchProviderException, InvalidAlgorithmParameterException{
	         
	    	  KeyGenerator kgen=KeyGenerator.getInstance(KEY_ALGORITHM);
	    	  kgen.init(128, new SecureRandom(strDefaultKey.getBytes()));  
	    	  SecretKey secretKey = kgen.generateKey(); 
	    	  byte[] enCodeFormat = secretKey.getEncoded();
	    	  SecretKeySpec key = new SecretKeySpec(enCodeFormat, KEY_ALGORITHM); 
	    	  Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);// 创建密码器  
	    	  byte[] byteContent = password.getBytes(ENCODING);  
	    	  cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
	    	  byte[] result = cipher.doFinal(byteContent); 
	    	  return result; // 加密  
	      }
	     /**
	       * AES解密
	       * @param data        待解密数据为字节数组
	       * @param keyByte    密钥
	       */
	      public static byte[] decrypt(byte[] password) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, NoSuchProviderException, InvalidAlgorithmParameterException {
	    	  KeyGenerator kgen = KeyGenerator.getInstance(KEY_ALGORITHM);  
	    	  kgen.init(128, new SecureRandom(strDefaultKey.getBytes())); 
	    	  SecretKey secretKey = kgen.generateKey();  
	    	  byte[] enCodeFormat = secretKey.getEncoded();
	    	  SecretKeySpec key = new SecretKeySpec(enCodeFormat, KEY_ALGORITHM);  
	    	  Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);// 创建密码器  
	    	  cipher.init(Cipher.DECRYPT_MODE, key);// 初始化  
	    	  byte[] result = cipher.doFinal(password); 
	    	  return result; // 解密
	    }
	      /**将二进制转换成16进制 **/         
	    private static String byteArr2HexStr(byte[] arrB) throws Exception {
	          int iLen = arrB.length;
	          // 每个byte用两个字符才能表示，所以字符串的长度是数组长度的两倍 
	          StringBuffer sb = new StringBuffer(iLen * 2);
	          for (int i = 0; i < iLen; i++) {
	              int intTmp = arrB[i];
	              // 把负数转换为正数 
	              while (intTmp < 0) {
	                  intTmp = intTmp + 256;
	              }
	              // 小于0F的数需要在前面补0 
	              if (intTmp < 16) {
	                  sb.append("0");
	              }
	              sb.append(Integer.toString(intTmp, 16));
	          }
	          return sb.toString();
	      }
	     // 将16进制转换为二进制
	      private static byte[] hexStr2ByteArr(String strIn) throws Exception {
	          byte[] arrB = strIn.getBytes();
	          int iLen = arrB.length;

	          // 两个字符表示一个字节，所以字节数组长度是字符串长度除以2 
	          byte[] arrOut = new byte[iLen / 2];
	          for (int i = 0; i < iLen; i = i + 2) {
	              String strTmp = new String(arrB, i, 2);
	              arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16);
	          }
	          return arrOut;
	      }

	     /**
	      * 测试
	     * @throws Exception 
	      */
	     public static void main(String[] args) throws Exception {
	    	 //加密
	         String data = "yian@suneee.com";
	         System.out.println("加密前：" + data);  
	         byte[] encryptResult = encrypt(data);
	         String encryptResultStr = byteArr2HexStr(encryptResult);  
	         System.out.println("加密后：" + encryptResultStr);	         
	         //解密  
	         byte[] decryptFrom = hexStr2ByteArr(encryptResultStr);  
	         byte[] decryptResult = decrypt(decryptFrom);  
	         System.out.println("解密后：" + new String(decryptResult));  

	     }
   
}
